﻿/*
  模块名称：菜单角色授权
  模块功能：对菜单进行选择，可以授权某角色可访问的页面和页面按钮功能，二次开发人员，请理解代码后，再进行修改；
  当前版本：1.0
  开发人员：马立涛
  开始时间：2005-10-08
  
  修改时间：2008-10-3
  修 改 人：马立涛
 
 */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using Baimasoft.Manage.SqlServerDAL;
using HsTec.Mobile.Green.SqlServerDAL;

public partial class SysManage_Role_Edit : System.Web.UI.Page
{
    public string sHtml = "", ll = "";
    public string sFEHtml = ""; //文档类型
    public string sPCode = "";
    public string sPName = "";
    int nBtnCount = 0; //是否有被授权使用的按钮
    //protected BaiMaSoft.Conn.DataConn MyDataConn = new BaiMaSoft.Conn.DataConn();
    //protected BaiMaSoft.SysManage.UserManage UMConn = new BaiMaSoft.SysManage.UserManage();
    public string sEditType = "1", ThisCode = "";

    LogManage MyLog = new LogManage();


    RoleManage MyRM = new RoleManage();
    DataFile MyDF = new DataFile();

    protected void Page_Load(object sender, EventArgs e)
    {
        /*if ((string)Session["Baimasoft_User_LogonID"] == null)
        {
            Response.Redirect("../ReLogon.aspx");
        }*/
        if (ViewState["VHtml"] == null)
        {
            ViewState["VHtml"] = "";
        }
        if (!Page.IsPostBack )
        {      
            try
            {
                sEditType  = Request.QueryString["EditType"].ToString();
            }
            catch
            {
                sEditType = "1";
            }

            try
            {
                ThisCode = Request.QueryString["ThisCode"].ToString();
            }
            catch
            {
                ThisCode = "";
            }

            //文档类别
            string sFileExtension = ConfigurationManager.AppSettings["FileExtension"];
            string[] aFileExtension = sFileExtension.Split(',');
            int iFileExtension = aFileExtension.Length;

            FECount.Value = iFileExtension.ToString().Trim();

            if (sEditType == "1")
            {
                RoleCode.Text = MyRM.GetMaxNumber("Sys_Role_Info", "Code");
                for (int i = 0; i < iFileExtension; i++)
                {
                    sFEHtml += aFileExtension[i].ToString().Trim() + "<input type=\"checkbox\" name=\"chkFileExtension\" value=\"" + aFileExtension[i].ToString().Trim() + "\" />&nbsp;&nbsp;";
                    if (i % 10 == 0 && i > 0)
                    {
                        sFEHtml += "<br />";
                    }
                }
            }
            else
            {
                string sTempFileExtension = MyDF.GetMyFileExtension(ThisCode);
                string[] aTempFE = sTempFileExtension.Split(',');

                for (int i = 0; i < iFileExtension; i++)
                {
                    string sFlag = "0";
                    for (int j = 0; j < aTempFE.Length; j++)
                    {
                        if (aFileExtension[i].ToString().Trim() == aTempFE[j].ToString().Trim())
                        {
                            sFlag = "1";
                            break;
                        }
                    }
                    if (sFlag == "1")
                    {
                        sFEHtml += aFileExtension[i].ToString().Trim() + "<input type=\"checkbox\" name=\"chkFileExtension\" checked =\"checked\" value=\"" + aFileExtension[i].ToString().Trim() + "\" />&nbsp;&nbsp;";
                    }
                    else
                    {
                        sFEHtml += aFileExtension[i].ToString().Trim() + "<input type=\"checkbox\" name=\"chkFileExtension\" value=\"" + aFileExtension[i].ToString().Trim() + "\" />&nbsp;&nbsp;";
                    }
                    if (i % 10 == 0 && i > 0)
                    {
                        sFEHtml += "<br />";
                    }
                }
            }



            ShowGrantTree();
        }
        sHtml = ViewState["VHtml"].ToString().Trim();
    }

    public void ShowGrantTree()
    {
        /* 控件树 */
        string sTreeHtml = "";
        string sRootLeaflessIconHtml = "<img height=\"20\" src=\"img/sys/root_leafless.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sRootSpreadIconHtml = "<img height=\"20\" src=\"img/sys/root_spread.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sMidLeaflessIconHtml = "<img height=\"20\" src=\"img/sys/mid_leafless.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sMidSpreadIconHtml = "<img height=\"20\" src=\"img/sys/mid_spread.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sRearLeaflessIconHtml = "<img height=\"20\" src=\"img/sys/rear_leafless.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sRearSpreadIconHtml = "<img height=\"20\" src=\"img/sys/rear_spread.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sFolderCloseIconHtml = "<img height=\"20\" src=\"img/sys/folder_close.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sFolderOpenIconHtml = "<img height=\"20\" src=\"img/sys/folder_open.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sPageUnselectedIconHtml = "<img height=\"20\" src=\"img/sys/page_unselected.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sVerticalIconHtml = "<img height=\"20\" src=\"img/sys/vertical.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        //string sButtonIconHtml = "<img height=\"20\" src=\"img/sys/button.gif\" width=\"19\" align=\"absMiddle\" border=\"0\">";
        string sBlankIconHtml = "<img src=\"img/sys/blank.gif\" align=\"absmiddle\" border=\"0\" WIDTH=\"19\" HEIGHT=\"20\">";

        string sUserRoleCode =  Session["Baimasoft_Role_Code"].ToString().Trim();
        SqlDataReader ShowGrantTreeReader2 = MyRM.GetMyMenuTree(sUserRoleCode); 
        int nPageCount = 0; //是否有被授权使用的页面
        while (ShowGrantTreeReader2.Read())
        {
            //从数据库存储过程所创建的临时表中取数据
            string sIndentVertical = ShowGrantTreeReader2["IndentVertical"].ToString().Trim(); //展开结点树时，缩进的结点前面是否有上(几)级结点的垂线
            string isLastSibling = ShowGrantTreeReader2["LastSibling"].ToString(); //是否同族的最后一个结点
            string isLeafed = ShowGrantTreeReader2["Leafed"].ToString(); //是否有叶子结点
            string sCode = ShowGrantTreeReader2["Menu_Code"].ToString(); // 结点编码
            string cType = ShowGrantTreeReader2["Type"].ToString(); //结点类型
            int iHomologID = (int)ShowGrantTreeReader2["Page_ID"]; //若是页面其对应的页面ID
            string sLabel = ShowGrantTreeReader2["Label"].ToString(); //结点标签

            //组合html语句
            string sLabelHtml = "&nbsp;" + sLabel;
            if (sCode.Equals("Men"))
            { //根结点
                string sRootHtml = "";
                if (isLeafed.Equals("0"))
                { //无子结点
                    sRootHtml = sRootLeaflessIconHtml + sFolderCloseIconHtml + sLabelHtml;
                    break;
                }
                else
                    sRootHtml = sRootSpreadIconHtml + sFolderOpenIconHtml + sLabelHtml;
                sTreeHtml = sTreeHtml + "<div>" + sRootHtml + "</div>";
            }
            else
            { //非根结点
                string sNodeHtml = "";
                // 处理缩进 
                string sIndentHtml = "";
                int i = 0;
                char cIsVertical;
                while (i < sIndentVertical.Length)
                {
                    cIsVertical = sIndentVertical[i];
                    if (cIsVertical == '0')
                        sIndentHtml = sIndentHtml + sBlankIconHtml;
                    else
                        sIndentHtml = sIndentHtml + sVerticalIconHtml;
                    i = i + 1;
                }

                // 结点 
                if (cType.Equals("1"))
                { //1.树枝结点
                    if (isLastSibling.Equals("0"))
                    { //2.非尾结点
                        if (isLeafed.Equals("1")) //3.有子结点
                            sNodeHtml = sMidSpreadIconHtml + sFolderOpenIconHtml + sLabelHtml;
                        else //3.无子结点
                            sNodeHtml = sMidLeaflessIconHtml + sFolderCloseIconHtml + sLabelHtml;
                    }
                    else
                    { //2.尾结点
                        if (isLeafed.Equals("1")) //3.有子结点
                            sNodeHtml = sRearSpreadIconHtml + sFolderOpenIconHtml + sLabelHtml;
                        else //3.无子结点
                            sNodeHtml = sRearLeaflessIconHtml + sFolderCloseIconHtml + sLabelHtml;
                    }
                }
                else if (cType.Equals("0"))
                { //1.树叶结点
                    nPageCount++;
                    string BtnInfo = "";
                    BtnInfo = MyBtnInfo (sUserRoleCode, iHomologID);
                    string sPageChkboxHtml = "<input type=\"checkbox\" name=\"chkPage\" value=\"" + iHomologID + "\" onclick=\"pageChkboxClick(this)\"/>&nbsp;&nbsp;" + BtnInfo;
                    if (isLastSibling.Equals("0")) //2.非尾结点
                        //sNodeHtml = sMidLeaflessIconHtml + sPageUnselectedIconHtml +sLabelHtml + sPageChkboxHtml + sBtnHtml;
                        sNodeHtml = sMidLeaflessIconHtml + sPageUnselectedIconHtml + sLabelHtml + sPageChkboxHtml;
                    else //2.尾结点
                        //sNodeHtml = sRearLeaflessIconHtml + sPageUnselectedIconHtml +sLabelHtml + sPageChkboxHtml + sBtnHtml;
                        sNodeHtml = sRearLeaflessIconHtml + sPageUnselectedIconHtml + sLabelHtml + sPageChkboxHtml;
                }
                sNodeHtml = sIndentHtml + sNodeHtml;
                sTreeHtml = sTreeHtml + "<div>" + sNodeHtml + "</div>";
            }
        }
        if (ShowGrantTreeReader2 != null)
            ShowGrantTreeReader2.Close();
        nBtnCount = MyRM.GetBtnCount();
        string sJS = "<script>form1.PCount.value=" + nPageCount + ";form1.BCount.value=" + nBtnCount + "</script>";
        sHtml = sTreeHtml + sJS;
        ViewState["VHtml"] = sHtml;
    }


    //授权时的按钮信息
    public string MyBtnInfo(string MyOrgRole, int PageID)
    {
        //取该页面下的所有有权使用的有效的按钮结点...
        int nBtnCount = 0;
        string sMyBtnHtml = "&nbsp;&nbsp;&nbsp;";
        //返回临时表中的信息
        SqlDataReader ShowGrantTreeReader3 = MyRM.GetMyBtnInfo(PageID);
        while (ShowGrantTreeReader3.Read())
        {
            nBtnCount++;
            string sBtnLabel = ShowGrantTreeReader3["BtnName"].ToString();
            int iBtnID = (int)ShowGrantTreeReader3["Btn_ID"];
            string sBtnLabelHtml = "&nbsp;&nbsp;&nbsp;<font color=\"blue\">" + sBtnLabel + "</font>";
            string sBtnChkboxHtml = "<input type=\"checkbox\" name=\"chkBtn\" value=\"" + PageID + "." + iBtnID + "\" onclick=\"btnChkboxClick(this)\"/>";
            sMyBtnHtml = sMyBtnHtml + sBtnLabelHtml + sBtnChkboxHtml;
        }
        if (ShowGrantTreeReader3 != null)
            ShowGrantTreeReader3.Close();
        return sMyBtnHtml;
    }
   
    //授权函数

    public int SaveGrantInfo(string sCode)
    {
        string pID = hidPageIDList.Value;
        string bID = hidBtnIDList.Value;
        string sPageBtnTotal = "";
        if (pID != "" && pID != null)
        {
            string[] sPageID = pID.Split('^');
            int nPageID = sPageID.Length;
            for (int i = 0; i < nPageID - 1; i++)
            {
                string sPageInfo = sPageID[i];
                string sBtnInfo = "";
                string[] sBtnID = bID.Split('^');
                int nBtnID = sBtnID.Length;
                for (int j = 0; j < nBtnID - 1; j++)
                {
                    string[] ssBtnID = sBtnID[j].Split('.');
                    if (sPageInfo == ssBtnID[0])
                    {
                        sBtnInfo += ssBtnID[1] + "^";
                    }
                }
                // sPageInfo  当前页面ID,sBtnInfo 当前按钮集合 ,sUserRole 当前用户角色
                sPageBtnTotal = sPageBtnTotal + sPageInfo + "." + sBtnInfo + "~";                
            }

            string sFE = HFEList.Value;
            //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sPageBtnTotal + "');</script>");
            int iback = MyRM.InsertRoleGrantInfo(sCode, sPageBtnTotal, sFE);
            if (iback == 1)
            {
                return 1; //授权成功
            }
            else
            {
                return 0; //授权失败
            }
        }
        else
        {
            return 2; //没有授权信息
        }
    }
    protected void GrantBtn1_ServerClick(object sender, EventArgs e)
    {
        
    }
    protected void SaveInfo_Click(object sender, EventArgs e)
    {
        string sUserRole = Session["Baimasoft_Role_Code"].ToString().Trim();
        //保存角色信息
        string sRoleCode = RoleCode.Text.ToString().Trim();
        string sRoleName = RoleName.Text.ToString().Trim();
        string sRoleDescr = RoleDescr.Text.ToString().Trim();
        string sEditType = hidEditType.Value.ToString().Trim();
        string sEffective = Effective.SelectedValue.ToString().Trim();
        string sUserID = HChoiceID_1.Value.ToString().Trim();   //把角色分配给E用户ID

        if ((sRoleCode == "" || sRoleCode == null) && (sRoleName == "" || sRoleName == null))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色代码、角色名称不能为空!');</script>");
            return;
        }
        else if (sRoleCode == "" || sRoleCode == null)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色代码不能为空!');</script>");
            return;
        }
        else if (sRoleName == "" || sRoleName == null)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色名称不能为空!');</script>");
            return;
        }

        if (sRoleDescr.Length > 200)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色描述不能超过200个字!');</script>");
            return;
        }

        int iBackCode = MyRM.JudgeRoleCode (sRoleCode).Rows.Count ;  //判断角色代码是否重复
        int iBackName = MyRM.JudgeRoleName (sRoleName).Rows .Count ;  //判断角色名称是否重复

        if (sEditType == "1") // 新建
        {
            if (iBackCode == 1 && iBackName == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色代码、角色名称已创建!');</script>");
                return;
            }
            else if (iBackCode == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色代码已创建!');</script>");
                return;
            }
            else if (iBackName == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色名称已创建!');</script>");
                return;
            }

            MyRM.DelRoleGrantInfo(sRoleCode);      //删除相关授权信息            
            int iBackGrant = SaveGrantInfo(sRoleCode);  //保存授权信息

            //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert("+iBackGrant+");</script>");

            if (iBackGrant == 2)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择授权信息!');</script>");
                return;
            }

            int iBackSave = MyRM.InsertRoleInfo (sRoleCode, sRoleName, sRoleDescr, sUserRole, sEffective, sUserID); //保存角色信息

            if (iBackGrant == 1 && iBackSave == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('新建成功!');window.close();</script>");
                hidPageIDList.Value = "";  //清空页面授权信息
                hidBtnIDList.Value = "";  //清空按钮授权信息
                return;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('新建失败!');</script>");
                MyRM.DelRoleInfo(sRoleCode);
                MyRM.DelRoleGrantInfo(sRoleCode); 
                return;
            }
        }
        else if (sEditType == "2") //修改
        {
            string sPCode = OrRoleCode.Value.ToString().Trim();
            string sPName = OrRoleName.Value.ToString().Trim();
            //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sPCode + sPName + "');</script>");
            if (sPCode.Trim() != sRoleCode.Trim() && iBackCode == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色代码已创建!');</script>");
                return;
            }

            if (sPName.Trim() != sRoleName.Trim() && iBackName == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('角色名称已创建!');</script>");
                return;
            }

            MyRM.DelRoleGrantInfo(sRoleCode);      //删除相关授权信息     
            int iBackGrant = SaveGrantInfo(sRoleCode);  //保存授权信息   

            if (iBackGrant == 2)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择授权信息!');</script>");
                return;
            }

            int iBackSave = MyRM .UpdateRoleInfo (sRoleCode, sRoleName, sRoleDescr, sUserRole, sPCode, sEffective, sUserID); //修改角色信息
            if (iBackGrant == 1 && iBackSave == 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('修改成功!');;window.close();</script>");
                hidPageIDList.Value = "";  //清空页面授权信息
                hidBtnIDList.Value = "";  //清空按钮授权信息
                return;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('修改失败!');</script>");
                return;
            }
        }
    }
}
